package com.itheima.health.controller;


import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MenuService;
import com.itheima.health.service.UserService;
import com.itheima.health.pojo.Menu;
import com.itheima.health.utils.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @DubboReference
    private UserService userService;
    @DubboReference
    private MenuService menuService;
    @Autowired
    private PasswordUtil passwordUtil;

    @RequestMapping("/loginSuccess")
    public Result loginSuccess(){
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }

    @RequestMapping("/loginFail")
    public Result loginFail(){
        return new Result(false,MessageConst.LOGIN_FAIL);
    }


    @GetMapping("getusername")
    public Result getUsername(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal!=null && principal instanceof User){
            User user = (User) principal;
            return new Result(true,MessageConst.GET_USERNAME_SUCCESS,user.getUsername());
        }else {
            return new Result(false,MessageConst.GET_USERNAME_FAIL);
        }

    }

    @GetMapping("/getmenu")
    public Result getMenu(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        String username =null;
        if (principal!=null && principal instanceof User) {
            username = ((User) principal).getUsername();
        }
        com.itheima.health.pojo.User currentUser = userService.findByName(username);
        //根据用户id获取菜单(一级菜单),其中一级菜单中保存二级菜单
        List<Menu> menus = menuService.findByUserId(currentUser.getId());
        List<Map<String,Object>> menuList = new ArrayList<>();
        for (Menu menu : menus) {
            Map<String,Object> map = new HashMap<>();
            //一级菜单
            map.put("path",menu.getPath());
            map.put("title",menu.getName());
            map.put("icon",menu.getIcon());

            List<Map<String,Object>> children = new ArrayList<>();
            for (Menu menu1 : menu.getChildren()) {
                Map<String,Object> childrenMap = new HashMap<>();
                //二级菜单
                childrenMap.put("path",menu1.getPath());
                childrenMap.put("title",menu1.getName());
                childrenMap.put("linkUrl",menu1.getLinkUrl());
                children.add(childrenMap);
            }
            map.put("children",children);
            menuList.add(map);
        }

        return new Result(true,MessageConst.GET_MENU_SUCCESS,menuList);
    }

    @PreAuthorize("hasAuthority('USER_QUERY')")
    @GetMapping("findPage")
    public Result findPage(QueryPageBean queryPageBean){
        PageResult pageResult = userService.findPage(queryPageBean);
        if (pageResult==null){
            return new Result(false,MessageConst.QUERY_USER_FAIL);
        }
        return new Result(true,MessageConst.QUERY_USER_SUCCESS,pageResult);
    }

    @PreAuthorize("hasAuthority('USER_ADD')")
    @PostMapping("add")
    public Result userAdd(@RequestBody com.itheima.health.pojo.User user, Integer[] roleIds){
        //密码加密
        String encode = passwordUtil.encryptionPassword(null, user.getPassword());
        user.setPassword(encode);
        boolean flag = userService.userAdd(user,roleIds);
        if (!flag){
            return new Result(false,MessageConst.ADD_USER_FAIL);
        }
        return new Result(true,MessageConst.ADD_USER_SUCCESS);
    }

    @PreAuthorize("hasAuthority('USER_QUERY')")
    @GetMapping("findById")
    public Result findById(Integer id){
        com.itheima.health.pojo.User user = userService.findById(id);
        if (user == null){
            return new Result(false,MessageConst.QUERY_USER_FAIL);
        }
        return new Result(true,MessageConst.QUERY_USER_SUCCESS,user);
    }

    @PreAuthorize("hasAuthority('USER_EDIT')")
    @PostMapping("update")
    public Result update(@RequestBody com.itheima.health.pojo.User user,Integer[] roleIds){
        boolean flag = userService.update(user,roleIds);
        if (!flag){
            return new Result(false,MessageConst.EDIT_USER_FAIL);
        }
        return new Result(true,MessageConst.EDIT_USER_SUCCESS);
    }

    @PreAuthorize("hasAuthority('USER_DELETE')")
    @GetMapping("delete")
    public Result deleteByIf(Integer id){
        boolean flag = userService.deleteById(id);
        if (!flag){
            return new Result(false,MessageConst.DELETE_USER_FAIL);
        }
        return new Result(true,MessageConst.DELETE_USER_SUCCESS);
    }













}
